package znck.spring.serviceImp.util;

import java.io.BufferedReader;



import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import znck.spring.service.util.SyLog;
import znck.spring.service.util.SystemService;

@Service
public class SystemServiceImp implements SystemService {
	
	@Autowired
	SyLog syLogImp;
	
	@Override
	public String getProperty_key(String key) {
		// TODO Auto-generated method stub
		   Properties props_r = new Properties();
		   try {
				InputStreamReader in = new InputStreamReader(
						new FileInputStream(SystemServiceImp.class.getResource("/").toURI().getPath()+"SystemSet.properties"), "UTF-8");
				
				props_r.load(in);
				in.close();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		   
		   String str = props_r.getProperty(key);
		   
		   String pattern = "\\$\\{[a-zA-Z0-9\\_\\/\\:\\.]*\\}";    //"\\$"就是匹配"$","\\{"就是匹配"{"
		   Pattern r = Pattern.compile(pattern);
		   Matcher m = r.matcher(str);
		   StringBuffer sb = new StringBuffer();
		   while(m.find()) {
			   //sb逐渐将find处之前的值及该处匹配到的值添加到sb中
			   String sre = props_r.getProperty(str.substring(m.start() + 2, m.end() - 1));
			   if(sre != null && !sre.equals("")) {
				   m.appendReplacement(sb,sre);
			   }else {
				   syLogImp.error(SystemServiceImp.class, "SystemSet.properties配置文件中参数设置不能为空!");
			   }
		      }
		   //最后一次添加find之后的值
		   m.appendTail(sb);
		   //System.out.println(sb.toString());
		return sb.toString();
	}

	@Override
	public StringBuffer HttpsSend(String url, String type, String data) {
		// TODO Auto-generated method stub
		try {
			//建立连接x
			URL requestUrl = new URL(url);
			HttpsURLConnection conn = (HttpsURLConnection) requestUrl.openConnection();
			//使用MyX509TrustManager获取SSLSocketFactory对象
			TrustManager[] tm = { new MyX509TrustManager()};  
	        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
	        sslContext.init(null, tm, new java.security.SecureRandom());  
	        SSLSocketFactory ssf = sslContext.getSocketFactory(); 
	        conn.setSSLSocketFactory(ssf); 
	        conn.setDoInput(true);
	        conn.setDoOutput(true);
	        conn.setUseCaches(false);
	        conn.setRequestMethod(type.toUpperCase());  //必须大写
	        
	        //向输出流中写入数据
	        if(data != null&&(type.toUpperCase()).equals("POST")) {
	        	OutputStream outputStream = conn.getOutputStream();
	        	outputStream.write(data.getBytes("UTF-8"));
	        	outputStream.close();
	        }
	        
	        //得到输入
	        InputStream inputStream = conn.getInputStream();
	        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
	        BufferedReader reader = new BufferedReader(inputStreamReader);
	        
	        StringBuffer buffer = new StringBuffer();
	        String str = null;
	        while((str = reader.readLine())!=null) {
	        	buffer.append(str);
	        }
	        
	        reader.close();
	        inputStreamReader.close();
	        inputStream.close();
	        conn.disconnect();
	        
	        return buffer;
		} catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new StringBuffer("the request connection failed!");
	}

	@Override
	public String JavabeanTojson(Object obj) {
		// TODO Auto-generated method stub
		return JSONObject.fromObject(obj).toString();
	}

	@Override
	public JSONObject JavabeanToJSONObject(Object obj) {
		// TODO Auto-generated method stub
		return JSONObject.fromObject(obj);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T jsonTojavabean(Class<T> type, String json) {
		// TODO Auto-generated method stub
		JSONObject jsonObject = JSONObject.fromObject( json );  
		T bean = (T) JSONObject.toBean( jsonObject, type );
		return bean;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> T jsonTojavabean(Class<T> type, String json, Map<String, Class<T>> classmap) {
		// TODO Auto-generated method stub
		JSONObject jsonObject = JSONObject.fromObject( json );  
		T bean = (T) JSONObject.toBean( jsonObject, type,  classmap);
		return bean;
	}

	@Override
	public String JavabeanTojsonarray(Object obj) {
		// TODO Auto-generated method stub
		return JSONArray.fromObject(obj).toString();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> JSONArrayToListbean(Class<T> type, JSONArray jsonarray) {
		// TODO Auto-generated method stub
		//JSONArray.toArray转换为一个Object[]数组
		//JSONArray.toCollection转换为一个List<Object>对象
		return (List<T>) JSONArray.toCollection(jsonarray, type);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> JSONArrayToListbean(Class<T> type, String jsonarray) {
		// TODO Auto-generated method stub
		return (List<T>) JSONArray.toCollection(JSONArray.fromObject(jsonarray), type);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> JSONArrayToListbean(Class<T> type, JSONArray jsonarray,  Map<String, Class<T>> classmap) {
		// TODO Auto-generated method stub
		//JSONArray.toArray转换为一个Object[]数组
		//JSONArray.toCollection转换为一个List<Object>对象
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setRootClass(type);      //设置转换类型
		jsonConfig.setClassMap(classmap);   //设置要转换的特殊非基本类,比如List<Object>类型
		return (List<T>) JSONArray.toCollection(jsonarray, jsonConfig);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> JSONArrayToListbean(Class<T> type, String jsonarray,  Map<String, Class<T>> classmap) {
		// TODO Auto-generated method stub
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setRootClass(type);
		jsonConfig.setClassMap(classmap);
		return (List<T>) JSONArray.toCollection(JSONArray.fromObject(jsonarray), jsonConfig);
	}
	
	

}
